<template>
  <view class="detail-container">
    <!-- 基本信息部分 -->
    <view class="food-info">
      <image class="food-image" :src="foodInfo.img_url" mode="aspectFit"></image>
      <view class="food-name">{{foodInfo.name}}</view>
      <view class="food-category">类别：{{foodInfo.category}}</view>
    </view>

    <!-- 配方部分 -->
    <view class="section">
      <view class="section-title">配方</view>
      <view class="recipe-list">
        <view class="recipe-item" v-for="(item, index) in foodInfo.recipe" :key="index">
          <text class="recipe-number">{{index}}: </text>
          <view class="recipe-content">
            <template v-for="(part, pIndex) in splitRecipeText(item)" :key="pIndex">
              <text v-if="part.clickable" class="recipe-text clickable"
                @click="navigateToIngredient(part.text)">{{part.text}}</text>
              <text v-else class="recipe-text">{{part.text}}</text>
            </template>
          </view>
        </view>
      </view>
    </view>

    <!-- 步骤部分 -->
    <view class="section">
      <view class="section-title">步骤</view>
      <view class="steps-list">
        <view class="step-item" v-for="(item, index) in foodInfo.steps" :key="index">
          <view class="step-number">{{index + 1}}</view>
          <view class="step-content">
            <template v-for="(part, pIndex) in splitRecipeText(item)" :key="pIndex">
              <text v-if="part.clickable" class="step-text clickable"
                @click="navigateToIngredient(part.text)">{{part.text}}</text>
              <text v-else class="step-text">{{part.text}}</text>
            </template>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        id: '',
        foodInfo: {
          name: '',
          path: '',
          category: '',
          _id: '',
          recipe: [],
          steps: []
        },
        // 可点击跳转的特殊配料列表
        clickableIngredients: [
          '乳猪脆皮水',
          '烧鸡皮水',
          '琵琶鸭腌料',
          '叉烧酱',
          '烧鸭烧鹅味盐',
          '卤水',
          '炸葱油',
          '咸香鸡水',
          '烧鸭/烧鹅脆皮水',
          '浓汤'
        ]
      }
    },
    onLoad(options) {
      if (options.id) {
        this.id = options.id;
        this.getFoodDetail();
      }
    },
    methods: {
      getFoodDetail() {
        uniCloud.callFunction({
          name: 'get_food_detail',
          data: {
            id: this.id
          }
        }).then(res => {
          if (res.result.data) {
            this.foodInfo = res.result.data;
          }
        }).catch(err => {
          uni.showToast({
            title: '获取详情失败',
            icon: 'none'
          });
        });
      },
      // 将文本拆分为可点击和不可点击部分
      splitRecipeText(text) {
        // 如果 text 是数组，处理每个元素
        if (Array.isArray(text)) {
          const result = [];
          text.forEach(item => {
            // 检查当前项是否包含可点击配料
            item = item + '\n';
            const hasClickable = this.clickableIngredients.some(ingredient => item.includes(ingredient));

            if (hasClickable) {
              // 如果包含可点击配料，进行拆分处理
              const parts = this.processText(item);
              result.push(...parts);
            } else {
              // 如果不包含可点击配料，直接添加为不可点击项
              result.push({
                text: item,
                clickable: false
              });
            }
          });
          return result;
        }
        // 如果是单个字符串，直接处理
        return this.processText(text);
      },

      // 处理单个文本字符串
      processText(text) {
        const parts = [];
        let remainingText = text;

        // 查找所有可点击的配料
        this.clickableIngredients.forEach(ingredient => {
          if (text.includes(ingredient)) {
            const index = remainingText.indexOf(ingredient);
            if (index !== -1) {
              // 添加配料前的文本
              if (index > 0) {
                parts.push({
                  text: remainingText.substring(0, index),
                  clickable: false
                });
              }

              // 添加配料（可点击部分）
              parts.push({
                text: ingredient,
                clickable: true
              });

              // 更新剩余文本
              remainingText = remainingText.substring(index + ingredient.length);
            }
          }
        });

        // 添加剩余的文本
        if (remainingText) {
          parts.push({
            text: remainingText,
            clickable: false
          });
        }

        return parts;
      },
      // 跳转到对应配料的详情页
      async navigateToIngredient(ingredientName) {
        // 先获取对应配料的ID
        try {
          const res = await uniCloud.callFunction({
            name: 'get_food_by_name',
            data: {
              name: ingredientName
            }
          });

          if (res.result.data && res.result.data._id) {
            // 跳转到详情页
            uni.navigateTo({
              url: `/pages/detail/detail?id=${res.result.data._id}`
            });
          } else {
            uni.showToast({
              title: '未找到相关配料信息',
              icon: 'none'
            });
          }
        } catch (err) {
          uni.showToast({
            title: '获取配料信息失败',
            icon: 'none'
          });
        }
      }
    }
  }
</script>

<style lang="scss">
  .detail-container {
    padding: 20rpx;

    .food-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 40rpx;

      .food-image {
        width: 400rpx;
        height: 400rpx;
        border-radius: 20rpx;
        margin-bottom: 30rpx;
      }

      .food-name {
        font-size: 36rpx;
        font-weight: bold;
        margin-bottom: 20rpx;
      }

      .food-category {
        font-size: 28rpx;
        color: #666;
      }
    }

    .section {
      margin-bottom: 40rpx;

      .section-title {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 20rpx;
        padding-left: 20rpx;
        border-left: 8rpx solid #007AFF;
      }

      .recipe-list {
        padding: 0 20rpx;

        .recipe-item {
          padding: 10rpx 0;
          display: flex;
          flex-direction: column;
          align-items: flex-start;

          .recipe-number {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 10rpx;
            font-weight: bold;
          }

          .recipe-content {
            padding-left: 20rpx;
            width: 100%;
            white-space: normal;
            word-wrap: break-word;
          }

          .recipe-text {
            font-size: 28rpx;
            color: #333;
            line-height: 1.6;
            white-space: pre-wrap;

            &.clickable {
              color: #007AFF;
              text-decoration: underline;
              display: inline;
              white-space: nowrap;
            }

            &:active {
              opacity: 0.7;
            }
          }


        }
      }

      .steps-list {
        padding: 0 20rpx;

        .step-item {
          display: flex;
          align-items: flex-start;
          margin-bottom: 20rpx;

          .step-number {
            width: 40rpx;
            height: 40rpx;
            background-color: #007AFF;
            color: #fff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24rpx;
            margin-right: 20rpx;
            flex-shrink: 0;
          }

          .step-content {
            flex: 1;
            display: inline;
          }

          .step-text {
            font-size: 28rpx;
            color: #333;
            line-height: 1.6;

            &.clickable {
              color: #007AFF;
              text-decoration: underline;
              display: inline;

              &:active {
                opacity: 0.7;
              }
            }
          }
        }
      }
    }
  }
</style>